var app = getApp();
var _PAGE = 1;
var _PAGESIZE = 10;
var util = require("../../utils/util.js");
var FLAG = true;  
var mta = require('../../utils/mta_analysis.js');
var isseue_timer;
var ISSUE_TIME = 300;
var loads=true;
var startX = '', startY = '', issue_falg = false, issue_time = ISSUE_TIME;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    circleBg:["#E8E5FA","#FBF3CD","#FBE8E4","#E8E5FA","#FAEACE"],
    drawBg:["#1471FC","#FFDF40","#FA5D3A","#CE32FB","#FFAF23"],
    equipments_num: '../../images/equipments_num.png',
    equipments_time: '../../images/equipments_time.png',
    equipment_num:0, 
    equipment: [],
    equipment_id:'',
    device_no: '',
    info:{},
    addpopup:false,
    name:"",
    index:0,
    hasMore: false,
    loading: false,
    loadShow: false,
    open: false,//开关
    openfirst: true,//防止频繁点击
    screen: false,//显屏
    screenfirst: true,//防止频繁点击
    login_status:false,
    isShare: true,
    forced_flushing_time: 0,
    timing: false,
    pyScape: false,
    showmove: true,
    showclick: true,
    wash_regularly: 0,//定时冲洗，单位h，默认2
    screen_mode: 1,//1：已用天数、已用流量，2：已用天数、剩余流量，3：剩余天数、已用流量，4：剩余天数、剩余流量'
    screenList: [],//显示配置
    timedFlList: [],//冲洗配置
    is_delete: false,//是否删除只剩一台设备
    top: app.globalData._network_path + 'flow1.png',
    mid: app.globalData._network_path + 'flow2.png',
    bot: app.globalData._network_path + 'flow3.png',
    is_load:false
  },
  onLoad:function(options){
    mta.Page.init();
    var pid = '',that=this,way='';
    var pro = '';//推广商ID
    var cha = '';//渠道ID
    var is_move = wx.getStorageSync('is_move');
    var is_click = wx.getStorageSync('is_click');
    //二维码进入获取参数
    if (util.isExitsVariable(options.scene)) {
      var scene = util.sceneToArr(decodeURIComponent(options.scene));
      console.log(scene,"scne")
      if (util.isExitsVariable(scene.pid)) {
        pid = scene.pid;
        way = scene.way;
      }
      //推广商ID
      if (util.isExitsVariable(scene.pro)) {
        pro = scene.pro;
      }
      //渠道ID
      if (util.isExitsVariable(scene.cha)) {
        cha = scene.cha;
      }

      
    }
    if (util.isExitsVariable(options.pid)) {
      pid = options.pid;
      way = options.way;
    }
    //渠道ID
    if (util.isExitsVariable(options.pro)) {
      pro = options.pro;
    }
    //渠道ID
    if (util.isExitsVariable(options.cha)) {
      cha = options.cha;
    }
    if (pid != '') {
      wx.setStorageSync("pid", pid);
      wx.setStorageSync("way", way);
    }
    if(pro!=''){
      wx.setStorageSync("promoter", pro);//推广商ID
    }
    if (cha != '') {
      wx.setStorageSync("channel", cha);//渠道ID
    }
    //是否移动
    if (is_move == '' || is_move == undefined || is_move == null) {
      that.setData({
        showmove: false
      })
    }
    if (is_click == '' || is_click == undefined || is_click == null) {
      that.setData({
        showclick: false
      })
    }
    that.shareLogHistory()//浏览记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    var that = this;
    that.screenMode();//获取屏显模式配置
    _PAGE = 1;
    that.setData({
      equipment_num: 0,
    })
    app.loginStatus(function(){
      that.setData({
        login_status: true
      })
      that.userBindEquipment();
    },function(){
      that.setData({
        login_status: false,
        loadShow: true
      })
    });  
 
   
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.setData({
      loadShow: false
    })
    loads=true

  },
  
  //登录
  login(){
    wx.navigateTo({
      url: '/pages/user/login/login',
    })
  },
  //跳转到新增页面
  chooseFacility() {
    var token = wx.getStorageSync('token');
    //添加设备必须登录
    if (!util.isExitsVariable(token)) {
      wx.navigateTo({
        url: '/pages/user/login/login',
      })
      return false;
    }
    wx.navigateTo({
      url: '../addEquipment/addEquipment',
    })
  },
  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    var that = this;
    if (that.data.equipment_num == 1){
      that.equipmentDetail();
      return false;
    }
    _PAGE = 1;
    that.userBindEquipment();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (that.data.equipment_num < 1) {      
      return false;
    }
    if (!that.data.hasMore) {
      return false;
    }
    _PAGE++;
    that.setData({
      loading: true
    })
    that.userBindEquipment();
  },
  //绑定列表
  userBindEquipment:function(){
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    app.ajax({
      url: 'User/Equipmentlists/userBindEquipment',
      load: loads,
      data: { user_id: user_id, page: _PAGE, pageSize: _PAGESIZE },
      success: function (res) {
        wx.stopPullDownRefresh()
        if (res.data.code == 1000) {
          wx.setStorageSync('equipment_num', res.data.data.length);
          //若只有一台设备直接到详情页，否则列表页
          var equipment_num = that.data.equipment_num + res.data.data.length;
          that.setData({
            equipment_num: equipment_num
          })
          
          if(equipment_num==1){
            that.setData({
              equipment_id: res.data.data[0].equipment_id,
              device_no: res.data.data[0].device_no,
              open: res.data.data[0].switch_machine==0?false:true,
              screen: res.data.data[0].screen_status==0?true:false
            });
            that.equipmentDetail();
          }else if(equipment_num>1){
              //处理数据
              if (_PAGE == 1) {
                that.setData({
                  equipment: res.data.data,
                });
              } else {
                that.setData({
                  equipment: that.data.equipment.concat(res.data.data)
                });
              }
              //是否需要加载更多
              var hasMore = true;
              if (res.data.data.length < _PAGESIZE) {
                hasMore = false;
              }
              that.setData({
                hasMore: hasMore,
                loading: false
              })
            loads=false;
            }
        }else{
          if (_PAGE == 1) {
            that.setData({
              equipment_num: 0,
              equipment:[],
              hasMore: false,
              loading: false,
              is_delete: false
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              is_delete: false
            })
          }

        }
        that.setData({
          loadShow: true
        })
          
      }      
      
    })
  },
  //设备详情
  equipmentDetail: function () {
    var that = this;
    var equipment_id = that.data.equipment_id;
    app.ajax({
      url: "User/Equipmentlists/equipmentDetail",
      data: { "equipment_id": equipment_id },
      success: function (res) {
        wx.stopPullDownRefresh()        
        if (res.data.code == 1000) {
          that.setData({
            info: res.data.data,
            open: res.data.data.switch_machine == 0 ? false : true,
            screen: res.data.data.screen_status == 0 ? true : false,
            wash_regularly: res.data.data.wash_regularly,
            screen_mode: res.data.data.screen_mode
          })
        }
        that.setData({
          is_load:true
        })
        that.timedFlush(res.data.data.wash_regularly);//获取定时冲洗配置
      }
    })
  },
  //复制设备编号
  copyDeviceNo: function (e) {
    var dev = e.currentTarget.dataset.dev;
   
    wx.setClipboardData({
      data: dev,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            
          }
        })
      }
    })
  },
  // 开启添加弹窗
  addchannelpop: function (e) {
    var that = this;
    var equipment_id = e.currentTarget.dataset.equipment_id;
    var index = e.currentTarget.dataset.index;                 // 数组key值
    that.setData({
      addpopup: true,
      equipment_id: equipment_id,
      index:index
    })
    return false;
  },
  // 取消弹窗
  abolish() {
    var that = this;
    that.setData({
      addpopup: false
    })
  },
  //设备名称输入
  inputNameFun(e){
    var that = this;
    var name = e.detail.value;
    that.setData({
      name:name
    })

  },
  //确认修改
  sureSubmit() {
    var that = this;
    var equipment_id = that.data.equipment_id;
    var name = that.data.name;
    var index = that.data.index;
    var alias_name = "equipment[" + index + "].alias_name";  
   
    app.ajax({
      url:'User/Equipmentlists/editName',
      data: {"equipment_id": equipment_id,"name":name},
      success:function(res){
        app.showToast(res.data.message);
        if(res.data.code==1000){
          that.setData({
            [alias_name]: name,
          });
        }
      }
    })
    that.setData({
      addpopup: false
    })
  },
  //跳转设备详情
  facilityDetail(e) {
    var equipment_id = e.currentTarget.dataset.equipment_id,that=this;
    wx.navigateTo({
      url: '../facilityDetail/facilityDetail?equipment_id=' + equipment_id,
    })
  },
  //查看配件详情
  facilityInformation(e) {
    var parts_id = e.currentTarget.dataset.parts_id;
    var equipment_id = e.currentTarget.dataset.equipment_id;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../facilityInformation/facilityInformation?parts_id=' + parts_id + "&equipment_id=" + equipment_id+"&id="+id,
    })
  },
   //用水量
  columnChart(){
    var that=this;
    that.setData({
      showclick: true
    })
    wx.setStorageSync('is_click', true);
      wx.navigateTo({
        url: '../columnChart/columnChart?equipment_id=' + this.data.equipment_id,
      })
  },

  //开关
  chooseone(e) {
    var that = this, opes = e.currentTarget.dataset.types, openfirst = that.data.openfirst;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if(type == 1 && status!=2){
      return false;
    }
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (openfirst == false) {
      app.showToast("为保护设备请勿频繁操作,请5秒后重试", 'none', 3000);
     
      return false;
    }
    if (opes == false) {
      that.powerOff(0)
      that.setData({
        open: true,
        openfirst: false,
      })
    } else {
      that.powerOff(1)
      that.setData({
        open: false,
        openfirst: false,
      })
    }

  },
  //冲洗
  choosetwo(e) {
    // app.showToast("冲洗成功", 'none', 2500);
    var that = this;
    var sn = that.data.device_no;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if(type == 1 && status!=2){
      return false;
    }
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    app.ajax({
      url: 'House/Issue/mandatory_rinse',
      data: { "sn": sn},
      success: function (res) {
        var forced_flushing_time = that.data.info.forced_flushing_time;
        that.setData({
          forced_flushing_time: forced_flushing_time,
          isShare: false
        })
        wx.vibrateLong();
        var timer = setInterval(function () {

          forced_flushing_time--;
          that.setData({
            forced_flushing_time: forced_flushing_time
          })
          if (forced_flushing_time <= 0) {
            clearInterval(timer);
            that.setData({
              isShare: true,
              forced_flushing_time: 0
            })
            app.showToast('亲,您的设备已经干净了~', 'none', 2500);
          }
          
        }, 1000)
      }
    })
  },
  //显屏
  choosethree(e) {
    var that = this, sceend = e.currentTarget.dataset.types, screenfirst = that.data.screenfirst;
    var type = that.data.info.type;
    var status = that.data.info.status;   
    if(type == 1 && status!=2){
      return false;
    } 
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }   
    if (screenfirst == false) {
      app.showToast("为保护设备请勿频繁操作,请5秒后重试", 'none', 3000);     
      return false;
    }
    if (sceend == false) {
      that.screen_status(0)
      that.setData({
        screen: true,
        screenfirst: false,
      })
    } else {
      that.screen_status(1)
      that.setData({
        screen: false,
        screenfirst: false,
      })
    }
  },
  //下发屏幕开关
  screen_status(screen_status){
    var that = this;
    var screen_status = screen_status;
    var sn = that.data.device_no;
    app.ajax({
      url: 'House/Issue/screen_status',
      data: { "sn": sn, "screen_status": screen_status },
      success: function (res) {
        wx.vibrateLong();
        app.showToast(res.data.message, 'none', 2500);
        setTimeout(() => {
          that.setData({
            screenfirst: true
          })
        }, 5000);
      }
    })
  },
  //发送指令
  //开关机
  powerOff(device_status){
    var that = this;
    var device_status = device_status;
    var sn = that.data.device_no;
    app.ajax({
      url:'House/Issue/power_off',
      data: { "sn": sn, "device_status": device_status},
      success:function(res){
        wx.vibrateLong();
        app.showToast(res.data.message, 'none', 2500);
        setTimeout(() => {
          that.setData({
            openfirst: true
          })
        }, 5000);
      }
    })
  },
  //续费
  goRenew: function (e) {
    var contract_id = e.currentTarget.dataset.contract_id;
    wx.navigateTo({
      url: '../user/renew/renew?contract_id=' + contract_id,
    })
  },
  //距离左边
  scrollLeft(e) {
    var that = this;
    if (e.detail.scrollLeft > 12) {
      that.setData({
        showmove: true
      })
      wx.setStorageSync('is_move', true);
    }
  },
  /**
* 计算滑动角度
* @param {Object} start 起点坐标
* @param {Object} end 终点坐标
*/
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.equipment.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      equipment: this.data.equipment
    })
    startX=e.changedTouches[0].clientX;
    startY=e.changedTouches[0].clientY;
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = startX,//开始X坐标
      startY = startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.equipment.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      equipment: that.data.equipment
    })
  },
  //解绑 
  flDetele(e){
    var that = this, equipment_id = e.currentTarget.dataset.equipment_id;
    wx.showModal({
      title: '是否解绑',
      content: '解绑之后将无法查看该设备信息',
      showCancel: true,
      cancelText: '算了吧',
      cancelColor: '#6CA9FF',
      confirmText: '解绑',
      confirmColor: '#FF9E7D',
      success: function (res) {
        //确定事件
        if (res.confirm == true) {
          app.ajax({
            url: 'User/Equipmentlists/unBindEquipment',
            data: { "equipment_id": equipment_id},
            success: function (res) {
              if (res.data.code == 1000) {
                var equipment = that.data.equipment;
                if (equipment.length == 2) {
                  that.setData({
                    equipment_num: 0,
                    is_delete: true
                  })
                }
                that.userBindEquipment();//重新调取接口
                app.showToast('删除成功');
              } else {
                app.showToast(res.data.message);
              }
            }
          })
          //that.handlePoster();
        }
        //取消事件
        if (res.cancel == true) {
          // app.showToast('取消了就没办法分享给好友了')
        }
      },
    })
  },
  //跳转远程遥控页面
  navRemoteControl() {
    var equipment_id = this.data.equipment_id;
    wx.navigateTo({
      url: '../remoteControl/remoteControl?equipment_id=' + equipment_id
    })
  },
  //定时冲洗
  choosefour(e) {
    var that = this, sn = that.data.device_no,
      index = e.currentTarget.dataset.index;
    var type = that.data.info.type;
    var status = that.data.info.status;
   if(type == 1 && status!=2){
     return false;
   }
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    var timedFlList = that.data.timedFlList;
    if ((index + 1) < timedFlList.length) {
      index += 1;
    } else {
      index = 0;
    }
    
    app.ajax({
      url: "House/Issue/modified_timed_washing",
      data: { sn: sn, value: timedFlList[index].value },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast(parseInt(timedFlList[index].value) + '小时冲洗一次', 'none', 2500);
          that.setData({
            wash_regularly: timedFlList[index].value
          })
        } else {
          app.showToast(res.data.message, 'none', 2500);
        }
      }
    })
  },
  //切换屏显
  choosefive(e) {
    var that = this, sn = that.data.device_no, index = e.currentTarget.dataset.index;
    var type = that.data.info.type;
    var status = that.data.info.status;
    if(type == 1 && status!=2){
      return false;
    }
    if (type != 1) {
      app.showToast("您的设备非智能设备无法使用该功能", 'none', 2500);
      return false;
    }
    if (status == 1) {
      app.showToast("您的设备已离线，无法进行该操作", 'none', 2500);
      return false;
    }
    if (!that.data.open) {
      app.showToast("请先开启设备", 'none', 2500);
      return false;
    }
    var screenList = that.data.screenList;
    if (index < screenList.length) {
      index += 1;
    } else {
      index = 1;
    }
    
    app.ajax({
      url: "House/Issue/switch_screen_display_mode",
      data: { sn: sn, value: [screenList[index - 1].time_mode, screenList[index - 1].flow_mode] },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast('模式' + ' ' + screenList[index - 1].description, 'none', 3000);
          that.setData({
            screen_mode: index
          })
        } else {
          app.showToast(res.data.message, 'none', 2500);
        }
      }
    })

  },
  //获取屏显模式配置  
  screenMode() {
    var that = this;
    app.ajax({
      url: "Common/Conf/screenMode",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            screenList: res.data.data
          })
        }else{
          // console.log('我在这里', res.data.message);
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取定时冲洗配置
  timedFlush(wash_reguss) {
    var that = this;
    app.ajax({
      url: "Common/Conf/timedFlush",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          var havValue = false, arrshow = res.data.data;
          for (var i = 0; i < arrshow.length; i++) {
            if (arrshow[i].value == wash_reguss) {
              havValue = true;
            }
          }
          var obj = { 'description': wash_reguss + '小时冲洗一次', 'value': wash_reguss };
          if (!havValue) {
            arrshow.push(obj);
          }
          that.setData({
            timedFlList: arrshow
          })
        }
      }
    })
  },
  //重新下发套餐
  IssuePackage() {
    var that = this;
    clearInterval(isseue_timer);
    if (issue_falg && issue_time > 0) {
      app.showToast("请不要频繁下发套餐," + ISSUE_TIME / 60 + "分钟后再重新下发");
      return false;
    }
    app.showModal("", "是否需要重新下发套餐??", function () {
      issue_falg=true;
      that.issue(that.data.info.device_no);
    })
  },
  //下发套餐接口
  issue( device_no) {
    var that = this;
    app.ajax({
      url: "Common/Contract/issuePackage",
      data: { device_no: device_no },
      success: function (res) {
        app.showToast(res.data.message);
        if (res.data.code == 1000) {
          isseue_timer = setInterval(function () {
            issue_time -= 1;
          }, 1000)
        } else {
          issue_falg=false;
        }
      }
    })
  },
  //共享 pattern
  pattern(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../sharebox/pattern/pattern?ways=1' + '&id=' + id
    })
  },
  //客服
  helpCenter() {
    wx.navigateTo({
      url: '../customService/customService',
    })
  },
  //申请售后
  applyAfterSale: function (e) {
   var that = this;
    var device_no = that.data.device_no;
    var equipment_id = that.data.equipment_id;
    wx.navigateTo({
      url: '../user/applyAfterSale/applyAfterSale?device_no=' + device_no + '&equipment_id=' + equipment_id,
    })
  },
  //去商城
  goShop(){
      wx.switchTab({
        url:'../shopping/shoppingHome/shoppingHome'
      })
  },
  //浏览记录
  shareLogHistory() {
    var that = this;
    app.ajax({
      url: 'User/Browse/browseLog',
      method: "POST",
      data: { browse_page: 'pages/home/home' },//1是邀请好友 2分享详情 
      success: function (res) {
        if (res.data.code = 1000) {

        } else {

        }
      }

    })
  },

})